//
//  LGKConst.h
//  LGKit
//
//  Created by lyj on 06/24/2022.
//  Copyright (c) 2022 lyj. All rights reserved.
//

#ifndef LGKConst_h
#define LGKConst_h
#include <objc/runtime.h>
#import "LGKMetaMacros.h"
#import "LGKNoteManager.h"
#import <YJExtensions/YJExtensions.h>
#import <YJNetManager/YJNetManager.h>
#import <MJExtension/MJExtension.h>
#import <MarqueeLabel/MarqueeLabel.h>
#import <LGAlertHUD/LGAlertHUD.h>
#import <Masonry/Masonry.h>
#define LG_ScreenWidth      [UIScreen mainScreen].bounds.size.width
#define LG_ScreenHeight     [UIScreen mainScreen].bounds.size.height
#define LG_AppDelegate      [UIApplication sharedApplication].delegate

#define kApiParams(_ref)    (IsObjEmpty(_ref) ? @"" : _ref)
#define IsStrEmpty(_ref)    (((_ref) == nil) || ([(_ref) isEqual:[NSNull null]]) ||([(_ref)isEqualToString:@""]))
#define IsArrEmpty(_ref)    (((_ref) == nil) || ([(_ref) isEqual:[NSNull null]]) ||([(_ref) count] == 0))
#define IsObjEmpty(_ref)    (((_ref) == nil) || ([(_ref) isEqual:[NSNull null]]))

#define LG_ColorWithHexA(rgbValue,aValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:aValue]
#define LG_ColorWithHex(rgbValue) LG_ColorWithHexA(rgbValue,1.0f)

#define LG_ColorWithRGBA(r, g, b,a) [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a]
#define LG_ColorWithRGB(r, g, b) LG_ColorWithRGBA(r, g, b,1.0f)

#define LGImageName(name) [UIImage imageNamed:name]

#define LG_IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#define LG_IS_IPHONEX \
^(){\
BOOL iPhoneX = NO;\
if (UIDevice.currentDevice.userInterfaceIdiom != UIUserInterfaceIdiomPhone) {\
return iPhoneX;\
}\
if (@available(iOS 11.0, *)) {\
UIWindow *mainWindow = [[[UIApplication sharedApplication] delegate] window];\
if (mainWindow.safeAreaInsets.bottom > 0.0) {\
iPhoneX = YES;\
}\
}\
return iPhoneX;\
}()


#define LG_SysFont(value) [UIFont systemFontOfSize:value]
#define LG_SysWeightFont(value) [UIFont systemFontOfSize:value weight:UIFontWeightMedium]
#define LG_SysDynamicFont(value) [UIFont systemFontOfSize:LG_IS_IPAD ? value+2:value]


// 顶部状态栏高度（包括安全区）
#define LG_STATUS_BAR_HEIGHT \
^(){\
if (@available(iOS 13.0, *)) {\
    NSSet *set = [UIApplication sharedApplication].connectedScenes;\
    UIWindowScene *windowScene = [set anyObject];\
    UIStatusBarManager *statusBarManager = windowScene.statusBarManager;\
    return statusBarManager.statusBarFrame.size.height;\
} else {\
    return [UIApplication sharedApplication].statusBarFrame.size.height;\
}\
}()
// 导航栏Bar高度
#define LG_NAVIGATION_BAR_HEIGHT (44.0f)
// 导航栏整体高度
#define LG_STATUS_AND_NAVIGATION_BAR_HEIGHT ((LG_STATUS_BAR_HEIGHT) + (LG_NAVIGATION_BAR_HEIGHT))

// 齐刘海高度
#define LG_STATUS_NEAT_BANG_HEIGHT \
^(){\
if (LG_IS_IPHONEX) {\
    if (LG_STATUS_BAR_HEIGHT > 48){\
        return LG_STATUS_BAR_HEIGHT - 18;\
    }\
    return 24;\
} else {\
    return 0;\
}\
}()

// 底部安全区域远离高度
#define LG_BOTTOM_SAFE_HEIGHT \
^(){\
if (@available(iOS 13.0, *)) {\
NSSet *set = [UIApplication sharedApplication].connectedScenes;\
UIWindowScene *windowScene = [set anyObject];\
UIWindow *window = windowScene.windows.firstObject;\
return window.safeAreaInsets.bottom;\
} else if (@available(iOS 11.0, *)) {\
UIWindow *window = [UIApplication sharedApplication].windows.firstObject;\
return window.safeAreaInsets.bottom;\
}\
return 0;\
}()
// 底部栏高度
#define LG_TABBAR_HEIGHT (LG_BOTTOM_SAFE_HEIGHT + 49.0f)
// iPhoneX 底部home键高度
#define LG_BOTTOM_HOME_HEIGHT   (CGFloat)(LG_IS_IPHONEX ? (10) : (0))


#ifndef __OPTIMIZE__
#define LGLog(...) NSLog(@"*************************\n%s\n%d\n%@\n*************************",__func__,__LINE__,[NSString stringWithFormat:__VA_ARGS__])
#define NSLog(...) NSLog(__VA_ARGS__)
#else
#define LGLog(...) {}
#define NSLog(...) {}
#endif

/** 方法替换 */
static inline void lgk_exchangeImplementations(Class _Nonnull class, SEL _Nonnull originalSelector, SEL _Nonnull swizzledSelector) {
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);

    BOOL success = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
    if (success) {
        class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

static inline UIImage *_Nonnull lgk_getColorImg(UIColor *_Nonnull color,CGSize size) {
    UIView *bgColorView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, size.width,size.height)];
    bgColorView.backgroundColor = color;
    UIImage *bgImg = [UIImage yj_imageWithView:bgColorView];
    return bgImg;
}
/**
 倒计时

 @param seconds 倒计时时长
 @param countDownUpdate 剩余时间回调
 @param aSecondCallback 心跳（每秒一次）
 @param countDownCompletion 完成回调
 @return 倒计时 dispatch_source_t 对象，取消调用dispatch_source_cancel(dispatch_source_t source)函数
 */
static inline dispatch_source_t _Nonnull lgk_timerCountDown(NSInteger seconds, void (^ _Nullable countDownUpdate)(NSInteger interval), void (^ _Nullable aSecondCallback)(void), void (^ _Nullable countDownCompletion)(void)) {
    __block CFTimeInterval targetTime = CACurrentMediaTime() + seconds; // 最后期限
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0, queue);
    dispatch_source_set_timer(timer, dispatch_walltime(NULL,0), 1.0 / 60 * NSEC_PER_SEC, 0);// 每1/60秒执行一次
    __block NSInteger counter = 0;
    dispatch_source_set_event_handler(timer, ^{
        NSTimeInterval interval = targetTime - CACurrentMediaTime();
        if(interval > 0) {
            // 更新倒计时
            dispatch_async(dispatch_get_main_queue(), ^{
                if (counter % 60 == 0) {
                    if (countDownUpdate) countDownUpdate(seconds-counter/60);
                    if (aSecondCallback) aSecondCallback();
                }
                counter ++;
            });
        } else {
            // 倒计时结束，关闭
            dispatch_source_cancel(timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                if (countDownCompletion) countDownCompletion();
            });
        }
    });
    dispatch_resume(timer);
    return timer;
}

/** 延时方法 */
static inline void lgk_delay(NSTimeInterval time,void (^_Nullable callBlock) (void)){
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), callBlock);
}
#endif /* LGKConst_h */
